<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="statistics-page">
    <div class="header">
      <h2>系统统计</h2>
      <el-button @click="refreshAll" :loading="loading">
        <el-icon><Refresh /></el-icon>
        刷新统计
      </el-button>
    </div>

    <!-- 总览统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon orders">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ overallStats.totalOrders || 0 }}</div>
              <div class="stat-label">总订单数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon tickets">
              <el-icon><Tickets /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ overallStats.totalTickets || 0 }}</div>
              <div class="stat-label">总票务数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon users">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ overallStats.totalUsers || 0 }}</div>
              <div class="stat-label">总用户数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon revenue">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">¥{{ formatAmount(revenueStats.totalRevenue) }}</div>
              <div class="stat-label">总收入</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细统计 -->
    <el-row :gutter="20" class="detail-stats">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>订单状态分布</span>
            </div>
          </template>
          <div class="status-stats">
            <div class="status-item">
              <span class="status-label">待付款:</span>
              <span class="status-value pending">{{ overallStats.pendingOrders || 0 }}</span>
            </div>
            <div class="status-item">
              <span class="status-label">已付款:</span>
              <span class="status-value paid">{{ overallStats.paidOrders || 0 }}</span>
            </div>
            <div class="status-item">
              <span class="status-label">已取消:</span>
              <span class="status-value cancelled">{{ overallStats.cancelledOrders || 0 }}</span>
            </div>
            <div class="status-item">
              <span class="status-label">已退票:</span>
              <span class="status-value refunded">{{ overallStats.refundedOrders || 0 }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>今日统计</span>
            </div>
          </template>
          <div class="today-stats">
            <div class="today-item">
              <span class="today-label">今日订单:</span>
              <span class="today-value">{{ todayStats.todayOrders || 0 }}</span>
            </div>
            <div class="today-item">
              <span class="today-label">今日票务:</span>
              <span class="today-value">{{ todayStats.todayTickets || 0 }}</span>
            </div>
            <div class="today-item">
              <span class="today-label">新增用户:</span>
              <span class="today-value">{{ todayStats.todayUsers || 0 }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 座位统计 -->
    <el-card class="seat-stats">
      <template #header>
        <div class="card-header">
          <span>座位状态统计</span>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="seat-stat-item">
            <div class="seat-stat-label">总座位数</div>
            <div class="seat-stat-value">{{ overallStats.totalSeats || 0 }}</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="seat-stat-item">
            <div class="seat-stat-label">可用座位</div>
            <div class="seat-stat-value available">{{ overallStats.availableSeats || 0 }}</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="seat-stat-item">
            <div class="seat-stat-label">已占用座位</div>
            <div class="seat-stat-value occupied">{{ overallStats.occupiedSeats || 0 }}</div>
          </div>
        </el-col>
      </el-row>
      <el-progress 
        :percentage="seatOccupancyRate" 
        :color="getSeatOccupancyColor(seatOccupancyRate)"
        :stroke-width="8"
        style="margin-top: 20px"
      />
      <div class="occupancy-label">座位占用率: {{ seatOccupancyRate.toFixed(1) }}%</div>
    </el-card>

    <!-- 收入统计 -->
    <el-card class="revenue-card" v-if="userStore.isAdmin()">
      <template #header>
        <div class="card-header">
          <span>收入统计</span>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="revenue-item">
            <div class="revenue-label">总收入</div>
            <div class="revenue-value total">¥{{ formatAmount(revenueStats.totalRevenue) }}</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="revenue-item">
            <div class="revenue-label">待收入</div>
            <div class="revenue-value pending">¥{{ formatAmount(revenueStats.pendingRevenue) }}</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="revenue-item">
            <div class="revenue-label">退款金额</div>
            <div class="revenue-value refunded">¥{{ formatAmount(revenueStats.refundedAmount) }}</div>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Refresh, 
  Document, 
  Tickets, 
  User, 
  Money 
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { statisticsApi, type OverallStatistics, type TodayStatistics, type RevenueStatistics } from '@/api/statistics'

const userStore = useUserStore()

const loading = ref(false)

const overallStats = reactive<OverallStatistics>({
  totalOrders: 0,
  pendingOrders: 0,
  paidOrders: 0,
  cancelledOrders: 0,
  refundedOrders: 0,
  totalTickets: 0,
  validTickets: 0,
  usedTickets: 0,
  cancelledTickets: 0,
  totalUsers: 0,
  adminUsers: 0,
  normalUsers: 0,
  totalTrains: 0,
  activeTrains: 0,
  cancelledTrains: 0,
  totalSeats: 0,
  availableSeats: 0,
  occupiedSeats: 0
})

const todayStats = reactive<TodayStatistics>({
  todayOrders: 0,
  todayTickets: 0,
  todayUsers: 0
})

const revenueStats = reactive<RevenueStatistics>({
  totalRevenue: 0,
  pendingRevenue: 0,
  refundedAmount: 0
})

// 计算座位占用率
const seatOccupancyRate = computed(() => {
  const total = overallStats.totalSeats
  const occupied = overallStats.occupiedSeats
  return total > 0 ? (occupied / total) * 100 : 0
})

// 获取座位占用率颜色
const getSeatOccupancyColor = (rate: number) => {
  if (rate < 50) return '#67c23a'
  if (rate < 80) return '#e6a23c'
  return '#f56c6c'
}

// 格式化金额
const formatAmount = (amount: number) => {
  if (!amount) return '0.00'
  return amount.toFixed(2)
}

// 获取总体统计
const fetchOverallStatistics = async () => {
  try {
    const response = await statisticsApi.getOverallStatistics()
    Object.assign(overallStats, response.data)
  } catch (error) {
    console.error('获取总体统计失败:', error)
    ElMessage.error('获取总体统计失败')
  }
}

// 获取今日统计
const fetchTodayStatistics = async () => {
  try {
    const response = await statisticsApi.getTodayStatistics()
    Object.assign(todayStats, response.data)
  } catch (error) {
    console.error('获取今日统计失败:', error)
    ElMessage.error('获取今日统计失败')
  }
}

// 获取收入统计
const fetchRevenueStatistics = async () => {
  if (!userStore.isAdmin()) return
  
  try {
    const response = await statisticsApi.getRevenueStatistics()
    Object.assign(revenueStats, response.data)
  } catch (error) {
    console.error('获取收入统计失败:', error)
    ElMessage.error('获取收入统计失败')
  }
}

// 刷新所有统计
const refreshAll = async () => {
  loading.value = true
  try {
    await Promise.all([
      fetchOverallStatistics(),
      fetchTodayStatistics(),
      fetchRevenueStatistics()
    ])
    ElMessage.success('统计数据已更新')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  refreshAll()
})
</script>

<style scoped>
.statistics-page {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
}

.stat-item {
  display: flex;
  align-items: center;
  height: 88px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.stat-icon.orders {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.tickets {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.users {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.revenue {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.detail-stats {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  color: #303133;
}

.status-stats, .today-stats {
  padding: 10px 0;
}

.status-item, .today-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f5f5f5;
}

.status-item:last-child, .today-item:last-child {
  border-bottom: none;
}

.status-value.pending {
  color: #e6a23c;
  font-weight: bold;
}

.status-value.paid {
  color: #67c23a;
  font-weight: bold;
}

.status-value.cancelled {
  color: #909399;
  font-weight: bold;
}

.status-value.refunded {
  color: #f56c6c;
  font-weight: bold;
}

.today-value {
  font-weight: bold;
  color: #409eff;
}

.seat-stats, .revenue-card {
  margin-bottom: 20px;
}

.seat-stat-item {
  text-align: center;
  padding: 20px;
}

.seat-stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.seat-stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.seat-stat-value.available {
  color: #67c23a;
}

.seat-stat-value.occupied {
  color: #f56c6c;
}

.occupancy-label {
  text-align: center;
  margin-top: 10px;
  font-size: 14px;
  color: #606266;
}

.revenue-item {
  text-align: center;
  padding: 20px;
}

.revenue-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.revenue-value {
  font-size: 20px;
  font-weight: bold;
}

.revenue-value.total {
  color: #67c23a;
}

.revenue-value.pending {
  color: #e6a23c;
}

.revenue-value.refunded {
  color: #f56c6c;
}
</style>